package org.sky.security;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


//May I ask why you named this subclass almost same as subclass except the initial character?
//Sometime, it will make you confuse.
public class authenticationSuccessHandler implements AuthenticationSuccessHandler {
    //all the logger should be static as they don't need to be instanced every time after init a new object.
    private static Logger logger = LogManager.getLogger(authenticationSuccessHandler.class.getName());
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();

        String authority = userDetails.getAuthorities().iterator().next().getAuthority();
        if(!userDetails.isEnabled()){
            response.sendRedirect("Error.jsp");
        }
        StringBuilder logMessage = new StringBuilder();
        logMessage.append("IP Address: ").append(request.getRemoteAddr())
                .append("\tUser: ").append(userDetails.getUsername())
                .append("\tAuthority: ").append(authority);
        logger.trace(logMessage.toString());
       /* if(authority.equals(Authority.ROLE_USER.toString())){
            response.sendRedirect("TimeOut.jsp");
        }else {
            response.sendRedirect("index.jsp");
        }*/
        response.sendRedirect("index.jsp");

    }

}
